package org.mashart.pink.m.ws;

import org.mashart.pink.m.store.RecordManager;
import org.mashart.pink.m.store.FileManager;
import org.mashart.pink.m.store.Preferences;

/**
 * Connector for file I/O.
 * The GPS data are first stored in RecordStore.
 * Before terminating, the RecordStore is transfered into a file on the mobile device,
 * and the RecordStore is then deleted.
 */
public class FileConnector implements WsConnector{

    /**
     * Record Manager, implements the operation on record store.
     */
    private RecordManager recordManager;

    /**
     * File Connector, implements the operation on file system
     */
    private FileManager fileManager;

    /**
     * Configure.
     * @return
     */
    public int configure(){
        return 1;
    }

    /**
     * Initialize the record store.
     * @return
     */
    public int initialize(){
        fileManager = FileManager.getInstance();
        if ( !FileManager.isAPIAvailable() )
        {
            // File connection API is not available
            return -1;
        }
        // set the path for saving data files
        Preferences pref = Preferences.getInstance();
        String path = pref.get(Preferences.kPath);
        fileManager.setPath(path);
        if( fileManager.initialize() < 1 ){
            return -1;
        }
        
        // initialize the record manager
        recordManager = RecordManager.getInstance();
        // save the unsaved data, which are left by last run
        save();
        return 1;
    }

    /**
     * Store the string in bytes.
     * @param s a string
     * @return 1 if succeeded, -1 otherwise.
     */
    public int push(String s){
        return recordManager.insert(s.getBytes());
    }

    /**
     * Store the action command in bytes.
     * @param action action string
     * @return 1 if succeeded, -1 otherwise.
     */
    public int pushAction(String action){
        return push("action=" + action);
    }

    /**
     * Save the data in record store into a file.
     * If succeeded, delete the record store.
     * @return 1 if succeeded, -1 otherwise.
     */
    private int save(){
        int res = 1;
        if( recordManager.getNumRecords() > 0 ){
            // save the RecordStore
            res = fileManager.save(recordManager);
            if ( res > 0 ){
                recordManager.delete();
            }
        }
        return res;
    }

    /**
     * Close the record store. The records should remains on the mobile phone,
     * until the <code>RecordStoreConnector</code> is initialzed again.
     * However, depending on the implementation of the mobilephone,
     * it is possible that the RecordStore can not survive through battery changes, failures, or reboots.
     * @return
     */
    public int terminate(){
        return save();
    }
}
